import { AppDataSource } from '../config/database';
import { Device } from '../entity/Device';
import { getStrategy } from '../brand/strategyFactory';
import { In } from 'typeorm/find-options/operator/In';

export class DeviceManager {
    /**
     * 同步第三方设备信息（刷新数据库）
     */
    async syncDevices(userId: string, brand: string, accessToken: string): Promise<void> {
        const strategy = getStrategy(brand);
        const repo = AppDataSource.getRepository(Device);

        // 1. 获取第三方最新设备
        const latestDevices = strategy.getDeviceList(accessToken);
        const latestDeviceIds = (await latestDevices).map(d => d.did);

        // 2. 获取数据库当前设备
        const currentDevices = await repo.find({
            where: {userId, brand}
        });

        // 3. 计算差异
        const toAdd: Device[] = [];
        const toUpdate: Device[] = [];
        const toDeleteIds: string[] = [];

        // 3.1 找出需要删除的设备（在DB但不在最新列表）
        currentDevices.forEach(dbDevice => {
            if (!latestDeviceIds.includes(dbDevice.did)) {
                toDeleteIds.push(dbDevice.did);
            }
        });

        // 3.2 找出需要新增/更新的设备
        (await latestDevices).forEach(latestDevice => {
            const existing = currentDevices.find(d => d.did === latestDevice.did);

            if (existing) {
                // 需要更新的设备
                if (existing.name !== latestDevice.name || existing.type !== latestDevice.type) {
                    toUpdate.push(repo.create({
                        ...existing,
                        name: latestDevice.name,
                        type: latestDevice.type
                    }));
                }
            } else {
                // 需要新增的设备
                toAdd.push(repo.create({
                    did: latestDevice.did,
                    name: latestDevice.name,
                    type: latestDevice.type,
                    brand,
                    userId,
                    gid: null
                }));
            }
        });

        // 4. 原子性执行变更（事务保护）
        await AppDataSource.transaction(async manager => {
            // 删除
            if (toDeleteIds.length > 0) {
                await manager.delete(Device, {did: In(toDeleteIds)});
            }

            // 新增
            if (toAdd.length > 0) {
                await manager.save(toAdd);
            }

            // 更新
            if (toUpdate.length > 0) {
                await manager.save(toUpdate);
            }
        });
    }


  /**
   * 获取数据库中设备列表
   */
  async getUserDevices(userId: string): Promise<Device[]> {
    const repo = AppDataSource.getRepository(Device);
    return await repo.find({ where: { userId } });
  }

    /**
     * 获取设备状态信息
     * @param userId
     */
  async getDevicesWithStatus(userId: string): Promise<any[]> {
    const repo = AppDataSource.getRepository(Device);
    const devices = await repo.find({ where: { userId } });

    const results = devices.map(d => {
        return {
            did: d.did,
            name: d.name,
            type: d.type,
            brand: d.brand,
            online: true, // 默认全部在线
            status: this.getMockStatus(d.type)
        };
    });

    return results;
  }

    /**
     * 本地模拟设备状态返回，简化初始状态获取交互逻辑
     * @param type
     * @private
     */
    private getMockStatus(type: string): Record<string, any> {
        // 生成随机布尔值
        const randomBool = () => Math.random() > 0.5;

        // 生成指定范围内的随机整数
        const randomInt = (min: number, max: number) =>
            Math.floor(Math.random() * (max - min + 1)) + min;

        // 生成指定范围内的随机浮点数
        const randomFloat = (min: number, max: number, precision = 1) => {
            const value = Math.random() * (max - min) + min;
            return parseFloat(value.toFixed(precision));
        };

        // 从数组中随机选择一项
        const randomChoice = <T>(arr: T[]): T =>
            arr[Math.floor(Math.random() * arr.length)];

        switch (type.toLowerCase()) {
            // 传感器设备
            case 'mi_temp_hum_sensor': // 小米温湿度计
              return {
                temperature: randomFloat(15, 35), // 15-35°C
                humidity: randomInt(30, 90)       // 30-90%
              };

            case 'mi_air_sensor': // 空气质量检测仪
              return {
                pm25: randomInt(0, 300),        // PM2.5 0-300 μg/m³
                temperature: randomFloat(15, 35),
                humidity: randomInt(30, 90)
              };

            // 空调设备
            case 'mi_ac': // 小米空调
            case 'midea_ac': // 美的空调
                return {
                    power: randomChoice(['ON', 'OFF']),
                    target_temperature: randomFloat(16, 30),
                    mode: randomChoice(['cool', 'heat', 'dry', 'fan']),
                    fan_speed: randomChoice(['low', 'medium', 'high', 'auto'])
                };

            // 加湿器设备
            case 'mi_humidifier': // 小米加湿器
            case 'midea_humidifier': // 美的加湿器
                const isRunning = randomBool();
                return {
                    power: isRunning,
                    status: isRunning ? randomChoice(['running', 'paused']) : 'off',
                    mode: randomChoice(['auto', 'sleep', 'strong']),
                    target_humidity: randomInt(40, 70) // 40-70%
                };

            // 除湿器设备
            case 'mi_dehumidifier': // 小米除湿器
            case 'midea_dehumidifier': // 美的除湿器
                return {
                    power: randomBool(),
                    mode: randomChoice(['auto', 'sleep', 'dry']),
                    target_humidity: randomInt(30, 60) // 30-60%
                };

            // 空气净化器
            case 'mi_air_purifier': // 小米空气净化器
            case 'midea_air_purifier': // 美的空气净化器
                return {
                    power: randomBool(),
                    mode: randomChoice(['auto', 'silent', 'strong']),
                    fan_level: randomInt(1, 3) // 1-3档风速
                };

            // 默认返回
            default:
                return {
                    info: 'No mock status available',
                    type: type
                };
        }
    }



}
